package me.hbz.myblog.servlet;



import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import me.hbz.myblog.dao.UserDAO;
import me.hbz.myblog.domain.User;


@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.getRequestDispatcher("admin/login.jsp").forward(request, response);

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String username = request.getParameter("username");
		String password = request.getParameter("password");

		UserDAO userDAO = new UserDAO();
		try {
			User user = userDAO.findByUsernameAndPassword(username, password);
			if (user != null) {
				HttpSession session = request.getSession();
				session.setAttribute("admin", user);

				response.sendRedirect(request.getContextPath() + "/admin/index.do");
			} else {
				request.setAttribute("message", "用户名或密码错误，请重新输入!");
				request.getRequestDispatcher("admin/login.jsp").forward(request, response);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
